/**
 * Copyright (c) 时间, Tal.Ben 袁东昊 (ydonghao2@gmail.com).
 *
 * 版权
 */
package com.talben.soudian.ui;


import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject;
import org.kymjs.kjframe.http.HttpConfig;

import android.content.Intent;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import butterknife.InjectView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.talben.soudian.AppConfig;
import com.talben.soudian.AppContext;
import com.talben.soudian.AppManager;
import com.talben.soudian.R;
import com.talben.soudian.TDevice;
import com.talben.soudian.api.ApiHttpClient;
import com.talben.soudian.api.SouDianAPI;
import com.talben.soudian.base.BaseActivity;
import com.talben.soudian.bean.User;
import com.talben.soudian.util.SimpleTextWatcher;
import com.talben.soudian.util.StringUtils;


/**
 * @Title: LoginActivity.java
 * @Package com.talben.soudian.ui
 * @Description: 用户登陆界面
 * @author Tal.Ben
 * @date 2015年5月22日 下午10:01:11
 * @version v1.0
 */
public class LoginActivity extends BaseActivity {

    @InjectView(R.id.et_username)
    EditText mEtUserName;

    @InjectView(R.id.et_password)
    EditText mEtPassword;
    
    @InjectView(R.id.iv_clear_username)
    View mIvClearUserName;
    
    @InjectView(R.id.iv_clear_password)
    View mIvClearPassword;
    
    @InjectView(R.id.btn_login)
    Button mBtnLogin;
    
    @InjectView(R.id.btn_register)
    Button mBtnRegister;
    
    @InjectView(R.id.btn_forget_password)
    Button mBtnForgetPwd;
    
    private String mUserName;
    private String mPassword;
    
    private final TextWatcher mUserNameWatcher = new SimpleTextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            mIvClearUserName
                    .setVisibility(TextUtils.isEmpty(s) ? View.INVISIBLE
                            : View.VISIBLE);
        }
    };
    private final TextWatcher mPassswordWatcher = new SimpleTextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            mIvClearPassword
                    .setVisibility(TextUtils.isEmpty(s) ? View.INVISIBLE
                            : View.VISIBLE);
        }
    };
    
    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }
    
    @Override
    protected boolean hasBackButton() {
        return true;
    }
    
    @Override
    protected int getActionBarTitle() {
        return R.string.login;
    }
    
    @Override
	public void onClick(View v) {
		int id = v.getId();
        switch (id) {
        case R.id.iv_clear_username:
            mEtUserName.getText().clear();
            mEtUserName.requestFocus();
            break;
        case R.id.iv_clear_password:
            mEtPassword.getText().clear();
            mEtPassword.requestFocus();
            break;
        case R.id.btn_login:
            handleLogin();
            break;
        case R.id.btn_register:
        	UIHelper.gotoRegisterPage(LoginActivity.this);
        	break;
        case R.id.btn_forget_password:
        	UIHelper.gotoForgetPwd(LoginActivity.this);
        default:
            break;
        }
	}
    

	private void handleLogin() {

        if (!prepareForLogin()) {
            return;
        }

        // if the data has ready
        mUserName = mEtUserName.getText().toString();
        mPassword = mEtPassword.getText().toString();

        showWaitDialog(R.string.progress_login);
        SouDianAPI.login(mUserName, mPassword, mHandler);
    }
    
    private boolean prepareForLogin() {
        if (!TDevice.isNetworkReady(getApplicationContext())) {
            AppContext.showToastShort(R.string.tip_no_internet);
            return false;
        }
        String uName = mEtUserName.getText().toString();
        if (StringUtils.isEmpty(uName)) {
            AppContext.showToastShort(R.string.tip_please_input_username);
            mEtUserName.requestFocus();
            return false;
        }
        String pwd = mEtPassword.getText().toString();
        if (StringUtils.isEmpty(pwd)) {
            AppContext.showToastShort(R.string.tip_please_input_password);
            mEtPassword.requestFocus();
            return false;
        }
        return true;
    }

    private final AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			hideWaitDialog();
			String result;
			AppContext.showToast(R.string.tip_login_error_for_network);
			try {
				result = new String(arg2,"utf-8");
				JSONObject resJObj = new JSONObject(result);
				AppContext.showToast(resJObj.getString("error"));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
            
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			// 处理成功后的动作
			try {
				//保存cookieStore
				AppContext.setCookie(LoginActivity.this);
				//处理Json
                String result = new String(arg2,"utf-8");
                JSONObject resJObj = new JSONObject(result);
                User user = new User();
                if (resJObj.getString("result").equals("success")) {
					user.setuPassword(mPassword);
					user.setUname(resJObj.getString("name"));
					user.setuPhone(resJObj.getString("phone")); 
					user.setuEmail(resJObj.getString("email"));
					user.setuScore(resJObj.getString("score"));
					user.setuCoin(resJObj.getString("gold"));
					user.setuGiftLog(resJObj.getJSONObject("giftlog")
											.getJSONArray("rows")
											.getJSONObject(0)
											.getString("text"));
					user.setUaccount(user.getuPhone());
					
					AppContext.getInstance().saveUserInfo(user);
                    hideWaitDialog();
                    handleLoginSuccess();
				} else {
					AppContext.getInstance().cleanLoginInfo();
                    hideWaitDialog();
                    AppContext.showToast(resJObj.getString("error"));
				}
			} catch (Exception e) {
				e.printStackTrace();
                onFailure(arg0, arg1, arg2, e);
			}
		}
    };
    
    private void handleLoginSuccess() {
    	//跳到主界面.
    	AppManager.getAppManager().finishActivity(MainActivity.class);
    	UIHelper.gotoMainPage(LoginActivity.this);
        finish();
    }
    
	@Override
	public void initView() {
        mIvClearPassword.setOnClickListener(this);
        mIvClearUserName.setOnClickListener(this);
        mBtnLogin.setOnClickListener(this);
        mBtnForgetPwd.setOnClickListener(this);
        mBtnRegister.setOnClickListener(this);
        
        
        mEtUserName.addTextChangedListener(mUserNameWatcher);
        mEtPassword.addTextChangedListener(mPassswordWatcher);
	}

	@Override
	public void initData() {
		mEtUserName.setText(AppContext.getInstance()
	                .getProperty("user.uphone"));
		mEtPassword.setText(AppContext.getInstance()
                .getProperty("user.upassword"));
	}
	
}

